package com.pig4cloud.pigx.robot.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pigx.contract.api.feign.ContractOrderFeign;
import com.pig4cloud.pigx.contract.dto.ContractRobotPlaceOrderDTO;
import com.pig4cloud.pigx.contract.enums.ContractOrderEnum;
import com.pig4cloud.pigx.robot.entity.RobotConfig;
import com.pig4cloud.pigx.robot.rabbitmq.MQConstant;
import com.pig4cloud.pigx.robot.service.RobotConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Order(0)
@Component
public class AutoPlaceOrder implements ApplicationRunner {

	@Autowired
	private RobotConfigService robotConfigService;
	private List<RobotConfig> robotConfigList;
	@Autowired
	private RedisTemplate redis;
	private static long[] robotUserIds = {1000L, 2000L, 3000L, 4000L, 5000L, 6000L, 7000L, 8000L, 9000L, 10000L};
	private int userindex = 0;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		log.info("auto place order init...");
		init();
	}

	private void init() {
		initSymbol();
		placeorderThread();
	}

	private void initSymbol() {
		robotConfigList = robotConfigService.list(new QueryWrapper<RobotConfig>()
//						.in("symbol_id",1,2)
				.eq("status", "1")
				.eq("is_deleted", "0"));


	}

	@RabbitListener(queues = MQConstant.QUEUE_ROBOT_SYMBOL_UPDATE)
	@RabbitHandler
	private void updateSymbol() {
		initSymbol();

	}

	/**
	 * 下单
	 */
	private void placeorderThread() {
//
//		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
//		service.scheduleAtFixedRate(() -> {
//
//			long starttime = System.currentTimeMillis();
//			for (int i = 0; i < robotConfigList.size(); i++) {
//				try {
//
//					RobotConfig item = robotConfigList.get(i);
//					//if(!item.getSymbolName().equals("BTCUSDT")) continue;
//					String redis_key = item.getSymbolName() + "_last_price";
//					Object price = redis.opsForValue().get(redis_key);
//					if (price == null) {
//						log.error("robot auto place order error ,last price is null ");
//						continue;
//					}
//					BigDecimal lastprice = new BigDecimal(price.toString());
//					if (lastprice.compareTo(BigDecimal.ZERO) == 0) {
//						log.error("robot auto place order error ,last price is 0 ");
//						continue;
//					}
//					// 根据币对价格随机生成数量
//					BigDecimal quantity = PriceRule.getNum(lastprice);
//					quantity = quantity.setScale(4, RoundingMode.HALF_UP);
//					order(item, quantity, lastprice);
//
//				} catch (Exception ex) {
//					log.error(" auto place order error " + ex.getMessage());
//				}
//			}
//			log.info("--------------------auto order --------------------------------------");
//			log.info("--------------------" + (System.currentTimeMillis() - starttime) + "ms --------------------------------------");
//
//		}, 1000, 500, TimeUnit.MILLISECONDS);
	}

	//@GlobalTransactional(rollbackFor = Throwable.class)
	private void order(RobotConfig config, BigDecimal quan, BigDecimal lastprice) {
		//	ContractOrderNewDTO dto = new ContractOrderNewDTO();
		ContractRobotPlaceOrderDTO dto = new ContractRobotPlaceOrderDTO();
		//数量
		dto.setNum(quan);
		//价格
		dto.setPrice(lastprice);
		//方向
		dto.setSide(ContractOrderEnum.Side.MORE.getValue());
		//币对Id
		dto.setSymbolId(config.getSymbolId());
		dto.setUserId(robotUserIds[userindex]);
		if (++userindex > 9) {
			userindex = 0;
		}
		ContractRobotPlaceOrderDTO dtobid = new ContractRobotPlaceOrderDTO();
		BeanUtils.copyProperties(dto, dtobid);
		dtobid.setSide(ContractOrderEnum.Side.EMPTY.getValue());

		List<ContractRobotPlaceOrderDTO> dtolist = new ArrayList<ContractRobotPlaceOrderDTO>();
		dtolist.add(dto);
		dtolist.add(dtobid);

//		R r = contractOrderFeign.addMultiRobotKLine(dtolist, SecurityConstants.FROM_IN);
//		log.info("place order symbol :" + config.getSymbolName() + " quantity:" + quan + " price:" + lastprice + r.getMsg());
	}

	//@GlobalTransactional(rollbackFor = Throwable.class)
	private void bid(RobotConfig config, BigDecimal lastprice) {

	}

}
